<template>
  <div id="register">
    <a-spin :spinning="isSubmitting" :tip="l('Registering')">
      <h1 class="header">{{ l('UserRegistration') }}</h1>
      <a-form :model="form" @submit="save($event)" ref="formRef" :rules="rules">
        <!-- 管理员邮箱 -->
        <a-form-item name="emailAddress">
          <a-input
            v-model:value="form.emailAddress"
            :placeholder="l('EmailAddress')"
            required
            email
            type="email"
          >
            <template #prefix>
              <MailOutlined style="color: rgba(0, 0, 0, 0.25)" />
            </template>
          </a-input>
        </a-form-item>

        <!-- 用户账号 -->
        <a-form-item name="userName">
          <a-input
            v-model:value="form.userName"
            :placeholder="l('UserName')"
            required
            maxlength="32"
          >
            <template #prefix>
              <CloudOutlined style="color: rgba(0, 0, 0, 0.25)" />
            </template>
          </a-input>
        </a-form-item>

        <!-- 密码 -->
        <a-form-item name="password">
          <a-input type="password" v-model:value="form.password" :placeholder="l('Password')">
            <template #prefix>
              <UserOutlined style="color: rgba(0, 0, 0, 0.25)" />
            </template>
          </a-input>
        </a-form-item>
        <!-- 验证码 -->
        <a-form-item v-if="useCaptcha" name="CAPTCHA">
          <captcha
            v-model:value="form.verificationCode"
            ref="captcha"
            :placeholder="l('CAPTCHA')"
            :primaryKey="primaryKey"
            :type="captchaType"
            required
            @update:modelValue="getChange($event)"
          />
        </a-form-item>

        <a-form-item class="btn--container">
          <a-button type="primary" html-type="submit" block @click="save($event)">{{
            l('Register')
          }}</a-button>
        </a-form-item>
      </a-form>

      <a-row>
        {{ '已有账号？' }}
        <router-link to="/account/login">{{ '立即登录' }}</router-link>
      </a-row>
    </a-spin>
  </div>
</template>

<script lang="ts">
  import { AccountServiceProxy, RegisterInput, RegisterOutput } from '/@/shared/service-proxies';
  import { AppComponentBase } from '/@/shared/component-base';
  import { Captcha } from '../components';
  import AFormItem from 'ant-design-vue/es/form/FormItem';
  import { loginService } from '../login/login.service';
  import { abpService, appSessionService } from '/@/shared/abp';
  import { defineComponent } from 'vue';
  import { AppConsts } from '/@/abpPro/AppConsts';

  function hasErrors(fieldsError) {
    return Object.keys(fieldsError).some((field) => fieldsError[field]);
  }

  export default defineComponent({
    name: 'Register',
    components: {
      AFormItem,
      Captcha,
    },
    mixins: [AppComponentBase],
    data() {
      return {
        hasErrors,
        isSubmitting: false, // 提交中
        verificationImgUrl: undefined, // 验证码地址
        form: new RegisterInput(),
        rules: {
          userName: [
            {
              required: true,
              message: this.l('StoredCardUserNameInputDesc'),
              trigger: 'blur',
            },
          ],
          password: [
            {
              required: true,
              message: this.l('BaseDbLinkPasswordInputDesc'),
            },
            {
              min: abp.setting.getInt('Abp.Zero.UserManagement.PasswordComplexity.RequiredLength'),
              message: this.l(
                'MinLength',
                abp.setting.get('Abp.Zero.UserManagement.PasswordComplexity.RequiredLength'),
              ),
              trigg: 'blur',
            },
            {
              max: 32,
              message: this.l('MaxLength', 32),
              trigg: 'blur',
            },
          ],
          emailAddress: [
            {
              required: true,
              message: this.l('AdministratorMailboxesCannotBeEmpty'),
            },
            {
              pattern: '^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$',
              message: this.l('NotEmail'),
              trigger: 'blur',
            },
          ],
        },
        accountServiceProxy: new AccountServiceProxy(),
        registerInput: new RegisterInput(),
        loginService: loginService,
        saving: false,
        tmp: '',
        captchaTimestamp: 0,
      };
    },
    computed: {
      primaryKey: {
        get: function () {
          return this.tmp;
        },
        set: function (value: any) {
          if (value === null) return;
          this.tmp = value;
        },
      },
      captchaType() {
        // 验证码类型
        if (appSessionService.tenantId) {
          return AppConsts.settings.SharedSettings.UseCaptchaOnUserRegistration;
        } else {
          return AppConsts.settings.SharedSettings.UseCaptchaOnUserRegistration;
        }
      },
      useCaptcha() {
        return abpService.abp.setting.getBoolean(
          AppConsts.settings.SharedSettings.UseCaptchaOnUserRegistration,
        );
      },
    },
    watch: {
      'form.userName': {
        handler(newval, _oldval) {
          if (newval === '' || newval === null) {
            return;
          }
          this.primaryKey = newval;
        },
      },
    },
    methods: {
      getChange(val) {
        this.form.verificationCode = val;
      },
      save(e) {
        e.preventDefault();
        (this.$refs.formRef as any).validate().then(() => {
          this.isSubmitting = true;
          this.accountServiceProxy
            .register(this.form)
            .finally(() => {
              this.isSubmitting = false;
            })
            .then((result: RegisterOutput) => {
              if (!result.canLogin) {
                this.notify.success(this.l('SuccessfullyRegistered'));
              }
              this.isSubmitting = true;
              this.loginService.authenticateModel.userNameOrEmailAddress = this.form
                .emailAddress as any;
              this.loginService.authenticateModel.password = this.form.password;
              this.loginService.authenticate(
                () => {},
                () => {
                  if (this.$refs.captcha) {
                    (this.$refs.captcha as any).clearImg();
                  }
                },
                () => {
                  this.isSubmitting = false;
                },
              );
            });
        });
      },
      updateCaptchaTimestamp() {
        this.captchaTimestamp = new Date().getTime();
      },
    },
  });
</script>

<style lang="less" scoped>
  @import './register.less';
</style>
